const { baseUrl, CODE } = require('../../config/api.js')
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
  },

  /**
   * 组件的初始数据
   */
  data: {
    value: '',
    isRemark: false,
    color: '#666',
    postId: '',
    parentId: '',
    toUserId: '',
    placeholder: '添写你得评论',
    toUserTitle: ''
  },
  methods: {
    onInput(e) {
      const value = e.detail.value
      if (value) {
        this.setData({
          color: '#00b38a',
          value: value
        })
      } else {
        this.setData({
          color: '#666',
          value: ''
        })
      }
    },
    onBlur(e) {
      this.hide()
    },
    onSubmit() {
      // console.log('hi')
      if (!this.data.value) return
      const { postId, parentId, toUserId, value} = this.data
      const { nickName, id, avatarUrl} = app.globalData.userInfo
      const params = {
        parentId,
        postId,
        fromUserId: id,
        toUserId,
        content: value
      }
      // console.log('hi')
      wx.request({
        url: baseUrl + '/api/comment',
        method: 'POST',
        data: params,
        success: (res) => {
          res = res.data
          // console.log(res)
          if (res.code === CODE) {
            wx.showToast({
              title: '评论成功',
              icon: 'success'
            })
            params.fromUserTitle = app.globalData.userInfo.nickName
            params.toUserTitle = this.data.toUserTitle
            this.triggerEvent('remarkSuccess', params)
          } else {
            wx.showToast({
              title: '评论失败'
            })
          }
        },
        fail: (err) => {
          console.log(err)
        }
      })
      this.setData({
        isRemark: false
      })
    },
    show(options) {
      // console.log('最后',options)
      const { postId, parentId, toUserId, toUserName } = options
      // 有用户名参数，则更换placeholder
      const placeholder = toUserName ? `回复 ${toUserName} ` : '添写你得评论'
      this.setData({
        isRemark: true,
        postId,
        parentId: parentId || '',
        toUserId,
        placeholder,
        toUserTitle: toUserName || '',
      })
    },
    hide() {
      this.setData({
        isRemark: false
      })
    }
  }
})
